﻿using System.Data.Objects.DataClasses;
using System.Windows.Controls;
using AvalonDock;
using Dispatcher.Extensions;
using Dispatcher.Views;

namespace Dispatcher.Helpers
{
    /// <summary>
    /// Details List View Helper.
    /// </summary>
    internal class ListViewDetailsHelper
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ListViewDetailsHelper"/> class.
        /// </summary>
        /// <param name="listView">The list view.</param>
        public ListViewDetailsHelper(CommonListView listView)
        {
            ListView = listView;
        }

        /// <summary>
        /// Gets the list view.
        /// </summary>
        public CommonListView ListView { get; private set; }

        /// <summary>
        /// Tries the show details.
        /// </summary>
        /// <param name="dataGrid">The data grid.</param>
        public void TryShowDetails(DataGrid dataGrid)
        {
            var item = dataGrid.CurrentCell.Item;
            var column = dataGrid.CurrentCell.Column;
            if (column == null || item == null || !ListView.ColumnPropertyRelation.ContainsKey(column))
            {
                return;
            }

            var proprertyArgs = ListView.ColumnPropertyRelation[column];
            var value = item.GetType().GetProperty(proprertyArgs.PropertyName).GetValue(item);
            if (value == null)
            {
                return;
            }

            if (ListView.ModelValueViewRelation.ContainsKey(value))
            {
                ListView.ModelValueViewRelation[value].Activate();
            }
            else if (proprertyArgs.PropertyType.BaseType == typeof(RelatedEnd))
            {
                var entityType = proprertyArgs.PropertyType.GetGenericArguments()[0];
                var viewModel = ViewModelFactory.CreateEntityCollectionViewModel(entityType, value);
                var view = new ContentListView
                {
                    DataContext = viewModel,
                    Title = string.Format("{0} of {1}[{2}]",
                                          proprertyArgs.PropertyType.GetGenericArguments()[0].Name,
                                          item.GetType().Name,
                                          item.GetType().GetProperty("Id").GetValue(item))
                };

                view.Show(MainWindow.DockingManager, AnchorStyle.Bottom);
                ListView.ModelValueViewRelation.Add(value, view);
            }
        }
    }
}
